from datetime import timedelta
from flask import Flask,request
import json
import hashlib
import pymysql
import re

from sql import Login, Register, getUsers, editUser, deleteUser, addStudentNameId, deleteStudentNameId, editStudentNameId, getStudentCondition, getStudentNameId

# jwt token验证
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "gaokao_key_00"  # 设置 jwt 的秘钥
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(days=30)
jwt = JWTManager(app)

regex = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|substr|ascii|declare|exec|count|master|into|drop|execute)\\b|(\\*|;|\\+|'|%))"

def response(code, data):
    return json.dumps(data),code

def test(args):
    for prop in args:
        if isinstance(prop, str) and re.search(regex,prop):
            return False
    return True

@app.route('/')
def main():
    return 'success',200

@app.route('/api/user/login',methods=['POST'])
def login():
    try:
        args=request.get_json()
        name=args['name']
        password=args['password']

        if test([name, password]) == False:
            return response(500, {
                "success": False,
		"message": 'Input Error'
	    })

        password = password.encode('utf-8')
        password_hash = (hashlib.sha256(password).hexdigest())+'gaokao'
        password_hash = hashlib.md5(password_hash.encode("utf-8")).hexdigest()

        data=Login(name,str(password_hash))

        accessToken = create_access_token(identity = data["role"])
        return response(200,{
            "success":True,
            'data':{
                "token":'Bearer '+accessToken,
                "user":data
            }
        })
    except Exception as error:
        if error.args[0] == 200:
            return response(200, {
                "success": False,
                "message": error.args[1]
            })
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })
    
@app.route('/api/user/register',methods=['POST'])
def register():
    try:
        args=request.get_json()
        name=args['name']
        password=args['password']
        role=args['role']

        if test([name, password, role]) == False:
            return response(500, {
                "success": False,
                "message": 'Input Error'
            })

        password = password.encode('utf-8')
        password_hash = (hashlib.sha256(password).hexdigest())+'gaokao'
        password_hash = hashlib.md5(password_hash.encode("utf-8")).hexdigest()
        
        print(password_hash)
        data=Register(name,password_hash, role)
        return response(200,{
            "success":True,
            "data":{
                "user":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })
    
@app.route('/api/user', methods=['GET'])
@jwt_required()
def GetUsers():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })

        data=getUsers()
        return response(200,{
            "success":True,
            "data":{
                "users":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })

@app.route('/api/user/edit', methods=['POST'])
@jwt_required()
def EditUser():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })

        args = request.get_json()
        name = args['name']
        role = args['role']

        data=editUser(name, role)
        return response(200,{
            "success":True,
            "data":{
                "user":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })

@app.route('/api/user/delete', methods=['POST'])
@jwt_required()
def DeleteUser():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })

        args = request.get_json()
        name = args['name']

        data=deleteUser(name)
        return response(200,{
            "success":True,
            "data":{
                "user":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })

@app.route('/api/student',methods=['GET'])
@jwt_required()
def getStudent():
    try:
        role = get_jwt_identity()

        args=request.args
        name=args.get('name')
        id=args.get('id')

        if test([name, id]) == False:
            return response(500, {
                "success": False,
                "message": 'Input Error'
            })

        data=getStudentNameId(name,id)
        return response(200,{
            "success":True,
            "data":{
                "students":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })


@app.route('/api/student/condition',methods=['GET'])
@jwt_required()
def getStudent_condition():
    try:
        args=request.args
        condition=args.get('condition')

        data=getStudentCondition(condition)
        return response(200,{
            "success":True,
            "data":{
                "students":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })
    

@app.route('/api/student/edit',methods=['POST'])
@jwt_required()
def editStudent():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })
        args=request.get_json()
        name=args['name']
        id=args['id']
        chinese=args['chinese']
        math=args['math']
        english=args['english']
        physics=args['physics']
        history=args['history']
        chemistry=args['chemistry']
        biology=args['biology']
        politics=args['politics']
        geography=args['geography']

        if test([name, id, chinese, math, english, physics, history, chemistry, biology, politics, geography]) == False:
            return response(500, {
                "success": False,
                "message": 'Input Error'
            })

        data=editStudentNameId(name,id,chinese,math,english,physics,history,chemistry,biology,politics,geography)
        return response(200,{
            "success":True,
            "data":{
                "student":data
            }
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })

@app.route('/api/student/add',methods=['POST'])
@jwt_required()
def addStudent():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })
        args=request.get_json()
        name=args['name']
        id=args['id']
        chinese=args['chinese']
        math=args['math']
        english=args['english']
        physics=args['physics']
        history=args['history']
        chemistry=args['chemistry']
        biology=args['biology']
        politics=args['politics']
        geography=args['geography']

        if test([name, id, chinese, math, english, physics, history, chemistry, biology, politics, geography]) == False:
            return response(500, {
                "success": False,
                "message": 'Input Error'
            })

        data=addStudentNameId(name,id,chinese,math,english,physics,history,chemistry,biology,politics,geography)
        return response(200,{
            "success":True,
            "data":{
                "student":data
            }
        })
    except Exception as error:
        return response(507,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })
    
@app.route('/api/student/delete',methods=['POST'])
@jwt_required()
def deleteStudent():
    try:
        role = get_jwt_identity()
        if(role!=1):
            return response(401,{
                "success":False,
                "message":"用户无权限"
            })
        args=request.get_json()
        name=args['name']
        id=args['id']

        if test([name, id]) == False:
            return response(500, {
                "success": False,
                "message": 'Input Error'
            })

        data=deleteStudentNameId(name,id)
        return response(200,{
            "success":True,
        })
    except Exception as error:
        return response(500,{
            "success":False,
            "message":"Error{code}:{message}".format(code=error.args[0],message=error.args[1])
        })
    
